<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace app\api\controller;

use app\common\service\ApiService;
use app\common\service\BalanceService;
use app\common\service\InvestService;
use app\common\service\BourseService;
use think\Db;
/**
 * Description of Api
 *
 * @author Sammy Guergachi <sguergachi at gmail.com>
 */
class Api {
	//定时任务
   /*
    汇率 日志 行情
     */ 
	public function hlandlogandmarket(){
    var_dump(\app\common\service\SystemService::clearIpsLog());
		var_dump(\app\common\service\MarketService::getHuilv());
    $data = Db::table('tp_coin')->select();
     foreach ($data as $key => $val) {
          Db::table('tp_market')->insert([
                       'cid'=>$val['id'],
                       'price'=>$val['price'],
                       'date'=>strtotime(date('Y-m-d'))
          ]);
      }
	}

	/*
  行情
  */
	public function hangqing(){
		var_dump(\app\common\service\MarketService::getMarket());
	}
	
  public function updateLevel(){
    $res = Db::table('tp_user')->whereTime('vip_date','<',date('Y-m-d H:i:s'))->where('level','>',0)->where('level','<',3)->update(['level'=>0,'vip_next_days'=>5]);
    var_dump($res);
  }

  //10
	public function c1(){
    set_time_limit(0);
    $time = time();
    $date = date('Y-m-d H:i:s');
    $check = Db::table('tp_invest_profit_list')->whereTime('creat_date','>=',date('Y-m-d'))->find();
    if ($check) {
        die();
    }
    $profit_record = Db::table('tp_invest_profit_record')->where('status',0)->where('type','>=',30)->group('uid,wid')->field('uid,wid,sum(profit) profit')->select();
    foreach ($profit_record as $key => $val) {
      $uid= $val['uid'];
      switch ($val['wid']) {
        case '1':
          $remark = '团队收入';
          $type = 104;
          break;
        case '11':
          $remark = '城市合伙人团队收入';
          $type = 105;
          break;
        case '12':
          $remark = '营销经理团队收入';
          $type = 106;
          break;
        default:
          # code...
          break;
      }
      BalanceService::updateBalance($uid,$val['wid'],$val['profit'],$remark,$type);
    }
    //关闭30天的体验机器人
    $uidsss = Db::table('tp_invest_record')->where('config_id',1)->where('status',2)->whereTime('order_date','<',date('Y-m-d H:i:s',strtotime('-3 days')))->column('uid');
    Db::table('tp_invest_record')->where('uid','in',$uidsss)->update([
        'close_date'=>date('Y-m-d H:i:s'),
        'status'=>1,
        'open_type'=>2
    ]);  
    Db::table('tp_user')->where('id','in',$uidsss)->update(['static_profit_status'=>0,'team_profit_status'=>0]);
    Db::table('tp_invest_profit_record')->where('status',0)->where('type','>=',30)->update(['status'=>1]);
    
    $uids = Db::table('tp_invest_record')->where('status',2)->column('uid');
    $balance = Db::table('tp_user_balance')->where('uid','in',$uids)->where('wid',1)->column('balance','uid');
    $ty_balance = Db::table('tp_user_balance')->where('uid','in',$uids)->where('wid',10)->column('balance','uid');
    $config = Db::table('tp_invest_config')->column('*','id');
    foreach ($config as $key => &$val) {
      $has_rate = Db::table('tp_invest_config_rate')->where('rid',$val['id'])->whereTime('date',date('Y-m-d'))->order('id desc')->value('rate');
      if ($has_rate) {
        Db::table('tp_invest_rate')->where('robot',$val['id'])->update(['rate'=>$has_rate]);
        $val['rate'] = $has_rate;
      }

      $has = Db::table('tp_invest_rate')->where('robot',$val['id'])->whereTime('date','>',date('Y-m-d'))->find();
      if (!$has) {
        Db::table('tp_invest_rate')->insert([
          'rate'=>$val['rate'],
          'robot'=>$val['id'],
          'date'=>$date
        ]);
      }
    }
    // var_dump($data);die();
    $static_status = Db::table('tp_user')->where('id','in',$uids)->column('static_profit_status','id');
    $remark_arr = ['Huobi','Binance','CoinBase','HitBTC','OKEX'];
    $data = Db::table('tp_invest_record')->where('status',2)->order('id asc')->select();
    $config = Db::table('tp_invest_config')->where('id','>',0)->column('*','id');
    foreach ($data as $key => $val) {
      $uid = $val['uid'];
      if ($static_status[$uid] != 1) {
        continue;
      }
      if (!isset($balance[$uid])) {
        $balance[$uid] = 0;
      }
      if (!isset($ty_balance[$uid])) {
        $ty_balance[$uid] = 0;
      }
      $single_config = $config[$val['config_id']];
      $user_balance = $balance[$uid] + $ty_balance[$uid];
      //资金检测
      
      Db::startTrans();
      if(!isset($single_config['max'])){
          $single_config = Db::table('tp_invest_config')->where('id',$val['config_id'])->find();
      }  
      if ($single_config['max'] != 0 && $user_balance > $single_config['max']) {
        $user_balance = $single_config['max'];
      }
      $rate = $single_config['rate'];
      $num = $single_config['days'];
      $total_profit = $user_balance * $rate;
      $single_profit = $total_profit/$num;
      $has_profit = 0;
      for ($i=1; $i < $num + 1; $i++) {
        if ($i == $num) {
          $profit = $total_profit - $has_profit;
        } else {
          $single_rate = rand(-10,10);
          $profit = $single_profit * (1 + $single_rate/100);
          $has_profit += $profit;
        }
        $remark_id = array_rand($remark_arr);
        Db::table('tp_invest_profit_list')->insert([
            'uid'=>$uid,
            'amount'=>$profit,
            'creat_date'=>$date,
            'status'=>0,
            'order_id'=>$val['id'],
            'date'=>date('Y-m-d H:i:s',strtotime(date('Y-m-d').' '.rand(2,23).':'.rand(0,59).':'.rand(0,59))),
            'remark'=>$remark_arr[$remark_id]
          ]);
      }
      Db::commit();
    }

  }

  //30
  public function c2(){
    set_time_limit(0);
    $date = date('Y-m-d H:i:s');
    $data = Db::table('tp_invest_profit_list')->whereTime('date','<=',$date)->where('status',0)->select();
    foreach ($data as $key => $val) {
      $uid  = $val['uid'];
      if ($val['amount'] < 0) {
        continue;
      }
      Db::startTrans();
      Db::table('tp_invest_profit_record')->insert([
          'uid'=>$uid,
          'x_uid'=>0,
          'order_id'=>$val['order_id'],
          'profit'=>$val['amount'],
          'type'=>10,
          'wid'=>1,
          'date'=>$date
        ]);
      Db::table('tp_invest_profit_list')->where('id',$val['id'])->update(['status'=>1]);
      BalanceService::updateBalance($uid,1,$val['amount'],'交易收入',102,$val['id'],$val['remark']);
      $this->teamProfit($uid,$val['amount'],$val['id']);
      Db::commit();
    }
  }


    public function teamProfit($uid,$profit,$order_id){
      if ($profit <= 0) {
            return true;
        }
        $date = date('Y-m-d H:i:s');
        $user_info = Db::table('tp_user')->where('id',$uid)->find();
        $robot_level = $user_info['robot_level'];
        for ($i=1; $i < 5; $i++) { 
            $user_info = Db::table('tp_user')->where('id',$user_info['pid'])->find();
            if ($user_info) {
                if ($user_info['team_profit_status'] != 1) {
                    continue;
                }
                if ($user_info['robot_level'] < $robot_level) {
                  continue;
                }
                switch ($i) {
                    case 1:
                        $rate_name = 'static_one';
                        break;
                    case 2:
                        $rate_name = 'static_two';
                        break;
                    case 3:
                        $rate_name = 'static_three';
                        break;
                    case 4:
                        $rate_name = 'static_four';
                        break;
                    default:
                        # code...
                        break;
                }
                if ($user_info['level']<3) {
                    $rate = Db::table('tp_invest_level_config')->where('level',$user_info['level'])->value($rate_name);
                    $invite_profit = $rate * $profit;
                    if ($invite_profit > 0) {
                        // BalanceService::updateBalance($user_info['id'],1,$invite_profit,$i.'级团队收入',104,$order_id);
                        Db::table('tp_invest_profit_record')->insert([
                            'uid'=>$user_info['id'],
                            'x_uid'=>$uid,
                            'order_id'=>$order_id,
                            'profit'=>$invite_profit,
                            'type'=>30,
                            'wid'=>1,
                            'status'=>0,
                            'remark'=>'交易奖励',
                            'date'=>$date
                        ]);
                    }
                    
                } else if ($user_info['level'] == 3) {
                    $rate1 = Db::table('tp_invest_level_config')->where('id',4)->value($rate_name);
                    
                    $invite_profit1 = $rate1 * $profit;
                    if ($invite_profit1 > 0) {
                        // BalanceService::updateBalance($user_info['id'],1,$invite_profit1,$i.'级团队收入',104,$order_id);
                        Db::table('tp_invest_profit_record')->insert([
                            'uid'=>$user_info['id'],
                            'x_uid'=>$uid,
                            'order_id'=>$order_id,
                            'profit'=>$invite_profit1,
                            'type'=>30,
                            'wid'=>1,
                            'status'=>0,
                            'remark'=>'交易奖励',
                            'date'=>$date
                        ]);
                    }
                    

                    $rate2 = Db::table('tp_invest_level_config')->where('id',5)->value($rate_name);
                    $invite_profit2 = $rate2 * $profit;
                    if ($invite_profit2 > 0) {
                        // BalanceService::updateBalance($user_info['id'],11,$invite_profit2,$i.'级城市合伙人团队收入',105,$order_id);
                        Db::table('tp_invest_profit_record')->insert([
                            'uid'=>$user_info['id'],
                            'x_uid'=>$uid,
                            'order_id'=>$order_id,
                            'profit'=>$invite_profit2,
                            'type'=>31,
                            'status'=>0,
                            'wid'=>11,
                            'remark'=>'城市合伙人交易奖励',
                            'date'=>$date
                        ]);
                    }
                    

                } else if ($user_info['level'] == 4) {
                    $rate1 = 0;
                    $rate2 = Db::table('tp_invest_level_config')->where('id',6)->value($rate_name);
                    $invite_profit2 = $rate2 * $profit;
                    if ($invite_profit2 > 0) {
                        // BalanceService::updateBalance($user_info['id'],12,$invite_profit2,$i.'级营销经理团队收入',106,$order_id);
                        Db::table('tp_invest_profit_record')->insert([
                            'uid'=>$user_info['id'],
                            'x_uid'=>$uid,
                            'order_id'=>$order_id,
                            'profit'=>$invite_profit2,
                            'type'=>32,
                            'status'=>0,
                            'remark'=>'营销经理交易奖励',
                            'wid'=>12,
                            'date'=>$date
                        ]);
                    }
                }
            } else {
                return true;
            }
        }
    }
}
